﻿using Framework;
using UnityEngine;

namespace Game
{
    public class SceneObjectShadowComponent : ResourceComponent
    {
        private static readonly string _ShadowUrl = "Assets/Game/Assets/Shadow/Shadow.prefab";

        private GameObject _shadowGameObject;
        private Transform _shadowTransform;
        private Vector2 _shadowSize;
        private Vector2 _entitySize;
        private Transform _parentTransform;
        private SpriteRenderer _shadowRender;
        private int _sortingOrder;
        private int _sortingLayer;

        public SceneObjectShadowComponent()
        {
            Load(_ShadowUrl);
        }

        public void SetEntitySize(Vector2 size)
        {
            _entitySize = size;
            if (_shadowTransform != null)
            {
                float scale = _entitySize.x / _shadowSize.x;
                _shadowTransform.localScale = new Vector3(scale, scale, scale);
            }
        }

        public void SetSortingLayer(int layer)
        {
            _sortingLayer = layer;
            if (_shadowRender != null)
            {
                _shadowRender.sortingLayerID = _sortingLayer;
                _shadowRender.sortingOrder = _sortingOrder;
            }
        }
        
        public void SetSortingOrder(int order)
        {
            _sortingOrder = order;
            if (_shadowRender != null)
            {
                _shadowRender.sortingLayerID = _sortingLayer;
                _shadowRender.sortingOrder = _sortingOrder;
            }
        }

        public void SetParent(Transform parent)
        {
            _parentTransform = parent;
            if (_shadowTransform != null)
            {
                _shadowTransform.SetParent(parent, false);
            }
        }
        
        public override void Cancel()
        {
            if (_shadowGameObject != null)
            {
                Object.Destroy(_shadowGameObject);
                _shadowGameObject = null;
                _shadowTransform = null;
                _shadowRender = null;
            }
            base.Cancel();
        }

        protected override void OnLoadCompleted(Resource resource)
        {
            _shadowGameObject = Object.Instantiate(resource.GetAsset<GameObject>());
            _shadowTransform = _shadowGameObject.transform;
            BoxCollider2D collider2D = _shadowGameObject.GetComponent<BoxCollider2D>();
            _shadowSize = collider2D.size;
            collider2D.enabled = false;
            _shadowRender = _shadowGameObject.GetComponent<SpriteRenderer>();
            
            base.OnLoadCompleted(resource);
            
            SetEntitySize(_entitySize);
            SetSortingLayer(_sortingLayer);
            SetSortingOrder(_sortingOrder);
            SetParent(_parentTransform);
        }
    }
}